<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) wangyt <wangtom365@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Http\Controllers\Books;

use App\Http\Controllers\BaseController;
use App\Models\Books\BookSectionsModel;
use App\Models\Books\BooksModel;
use App\Models\Books\BookTextsModel;
use Illuminate\Http\Request;

class BookController extends BaseController
{
    public function index(Request $request)
    {
        return $this->showList($request);
    }

    /**
     * 详情.
     *
     * @param Request $request
     * @param int     $bookId
     * @param int     $sectionId
     */
    public function showDetail(Request $request, $bookId = 0, $sectionId = 0)
    {
        $data = [];
        // var_dump($sectionId);

        $result = (new BooksModel())->findOrFail($bookId);
        if ($result) {
            $result = $result->toArray();
        }
        $data['bookId'] = $bookId;
        $data['sectionId'] = $sectionId;
        $data['detail'] = $this->getBookInfo($bookId, $sectionId);

        return view('default.books.bookDetail', $data);
    }

    /**
     * 列表.
     *
     * @param mixed $category
     *
     * @return string
     */
    public function showList(Request $request, $category = '')
    {
        $page = $request->input('page', 0);
        $data = [];
        $where = [];
        $where['status'] = 1;
        if ($category) {
            $where['category'] = $category;
        }

        $result = (new BooksModel())->getListWithPaginate($where, $page);
        if (empty($result)) {
            return '没有获取到数据.请确认URL是否正确.';
        }
        // $data['category'] = (new PostCategoryModel())->getArticleCategory();

        // $data['categoryCount'] = (new BooksModel())->getListCountGroupByCategory();

        $data['listData'] = $result;

        return view('default.books.bookList', $data);
    }

    /**
     * 获取图书详情.
     *
     * @param int $bookId
     * @param int $sectionId
     */
    protected function getBookInfo($bookId = 0, $sectionId = 0)
    {
        $data = [
            'bookInfo' => [],
            'sectionList' => [],
            'sectionInfo' => [],
            'textInfo' => [],
        ];
        // 图书信息
        $data['bookInfo'] = (new BooksModel())->findOrFail($bookId)->toArray();

        // 章节信息
        $where = [
            'book_id' => $bookId,
        ];
        $data['sectionList'] = (new BookSectionsModel())->getList($where);

        if ($sectionId) {
            // 当前章节
            $data['sectionInfo'] = collect($data['sectionList'])->where('id', $sectionId)->first();
        } else {
            $data['sectionInfo'] = collect($data['sectionList'])->first();
        }
        // 章节详情
        if (!empty($data['sectionInfo']['text_id'])) {
            $data['textInfo'] = (new BookTextsModel())->find($data['sectionInfo']['text_id'])->toArray();
        }

        return $data;
    }
}
